package com.xuzimian.globaldemo.mq.rabbitmq.consumer;

import com.xuzimian.globaldemo.mq.rabbitmq.constants.Config;
import com.xuzimian.globaldemo.mq.rabbitmq.util.JmsMqUtil;
import org.junit.jupiter.api.Test;

import javax.jms.*;

/***
 * @Description rabbitmq jms客户端，amqp协议的点对点(队列模式)的消费者
 * @author xzm
 */
public class JMSQueueConsumer {

    @Test
    public void startProducer() throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = JmsMqUtil.createQueueConnection();
            //启动连接
            connection.start();
            //创建会话
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            //创建 Queue，需指定其对应的队列名称，消息生产者和消费者将根据它来发送、接收对应的消息。
            Queue myTestQueue = session.createQueue(Config.MQServerConect.QUQUE_DEFAULT_NAME);
            //消息消费者
            MessageConsumer consumer = session.createConsumer(myTestQueue);
            //消费者实现监听接口消费信息
            Session finalSession = session;
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        TextMessage textMessage = (TextMessage) message;
                        System.out.println(textMessage.getText());
                    } catch (JMSException e1) {
                        e1.printStackTrace();
                    }
                    try {
                        finalSession.commit();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }

                }
            });

        } finally {
            //关闭资源
            if (null != session) {
                session.close();
            }
            if (null != connection) {
                connection.close();
            }
        }
    }

}
